#include "./analog.h"
#include "../device/gpio.h"

namespace driver {

Analog analog;

using namespace device;

using A2 = PC<2>; // ADC0_IN12
using A3 = PC<3>; // ADC0_IN13

void Analog::init() {

    RCU_APB2EN |= RCU_APB2EN_PCEN | RCU_APB2EN_ADC0EN;
    RCU_AHBEN |= RCU_AHBEN_DMA0EN;

    config_analog<A2, A3>();

    RCU_CFG0 |= RCU_CFG0_ADCPSC;

    ADC_CTL0(ADC0) = ADC_CTL0_SM;
    ADC_CTL1(ADC0) = ADC_CTL1_CTN +
        ADC_CTL1_DMA +
        ADC_CTL1_ETSRC +
        ADC_CTL1_ETERC;
    ADC_RSQ0(ADC0) = 0x01 << 20;
    ADC_RSQ2(ADC0) = 12 + (13 << 5);
    ADC_SAMPT0(ADC0) = (0x07 << 6) + (0x07 << 9);
    ADC_CTL1(ADC0) |= ADC_CTL1_ADCON;

    ADC_CTL1(ADC0) |= ADC_CTL1_RSTCLB;
    for (; (ADC_CTL1(ADC0) & ADC_CTL1_RSTCLB) != 0x00 ;);
    ADC_CTL1(ADC0) |= ADC_CTL1_CLB;
    for (; (ADC_CTL1(ADC0) & ADC_CTL1_CLB) != 0x00 ;);

    DMA_INTC(DMA0) = 0x0F;
    DMA_CH0CTL(DMA0) = 0x00;
    DMA_CH0MADDR(DMA0) = reinterpret_cast<uint32_t>(m_values);
    DMA_CH0PADDR(DMA0) = reinterpret_cast<uint32_t>(& ADC_RDATA(ADC0) );
    DMA_CH0CNT(DMA0) = 2;
    DMA_CH0CTL(DMA0) = 0x0521 + 0x80;

    ADC_CTL1(ADC0) |= ADC_CTL1_SWRCST;
}

}
